package com.seeyon.apps.hems.kit;

import com.seeyon.apps.hems.enums.BarchLabelPrintEnum;
import com.seeyon.cap4.form.bean.*;
import com.seeyon.cap4.form.modules.engin.base.formData.CAP4FormDataManager;
import com.seeyon.cap4.form.service.CAP4FormManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.ModuleType;
import com.seeyon.ctp.common.content.mainbody.CtpContentAllBean;
import com.seeyon.ctp.common.content.mainbody.MainbodyService;
import com.seeyon.ctp.common.content.mainbody.MainbodyStatus;
import com.seeyon.ctp.common.content.mainbody.MainbodyType;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.common.po.content.CtpContentAll;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumBean;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.util.DateUtil;
import com.seeyon.ctp.util.UUIDLong;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;

import java.sql.Timestamp;
import java.util.*;

public class FormKit {
    private static final Log log = CtpLogFactory.getLog(FormKit.class);
    /*《入库标签打印模板》底表表单编号*/
    private static String unFlowformCode = AppContext.getSystemProperty("hems.rkbqdymbCode");
    /*打印状态枚举编码*/
    private static String dyztNumber = AppContext.getSystemProperty("hems.dyztNumber");
    /*《日志记录台账》底表表单编号*/
    private static String rzjltaCode = AppContext.getSystemProperty("hems.rzjltzCode");
    private static EnumManager enumManagerNew = (EnumManager) AppContext.getBean("enumManagerNew");
    private static CAP4FormManager cap4FormManager = (CAP4FormManager) AppContext.getBean("cap4FormManager");
    private static CAP4FormDataManager cap4FormDataManager = (CAP4FormDataManager) AppContext.getBean("cap4FormDataManager");

    /**
     * 入库标签打印数据信息封装
     *
     * @param formDataId
     * @return
     */
    public static Map<String, Object> batchLabelPrintingDatas(Long formDataId) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        FormDataMasterBean formDataMasterBean = getDataMasterBeanById(formDataId);
        if (formDataMasterBean == null) {
            return dataMap;
        }
        /*遍历入库标签打印枚举，封住标签内容信息*/
        for (BarchLabelPrintEnum barchLabelPrintEnum : BarchLabelPrintEnum.values()) {
            String fieldName = formDataMasterBean.getFormTable().getFieldBeanByDisplay(barchLabelPrintEnum.getValue()).getName();
            dataMap.put(barchLabelPrintEnum.getKey(), formDataMasterBean.getFieldValue(fieldName));
        }
        return dataMap;
    }

    /**
     * 更新入库标签打印数据打印状态
     *
     * @param formDataId
     * @return
     */
    public static void updateBatchLabelPrintState(Long formDataId) {
        try {
            FormBean formBean = cap4FormManager.getFormByFormCode(unFlowformCode);
            FormDataMasterBean formDataMasterBean = cap4FormManager.getDataMasterBeanById(formDataId, formBean, null);
            List<FormDataMasterBean> formDataMasterBeanList = new ArrayList<FormDataMasterBean>();
            List<String> fieldList = new ArrayList<String>();
            String fieldName = formDataMasterBean.getFormTable().getFieldBeanByDisplay("打印状态").getName();

            String sjdhVlaue = StrKit.str(formDataMasterBean.getFieldValue(formDataMasterBean.getFormTable().getFieldBeanByDisplay("入库单号").getName()));
            CtpEnumBean ctpEnumBean = enumManagerNew.getEnumByProCode(dyztNumber);
            List<CtpEnumItem> itemList = enumManagerNew.getEmumItemByEmumId(ctpEnumBean.getId());
            if (!itemList.isEmpty()) {
                for (CtpEnumItem ctpEnumItem : itemList) {
                    String showValue = ctpEnumItem.getShowvalue();
                    if ("已打印".equals(showValue)) {
                        log.info("送检单号【" + sjdhVlaue + "】已打印枚举ID:" + ctpEnumItem.getId());
                        formDataMasterBean.addFieldValue(fieldName, ctpEnumItem.getId());
                        fieldList.add(fieldName);
                    }
                }
            }
            /*更新标签打印状态*/
            cap4FormManager.saveOrUpdateFormData(formDataMasterBean, formBean.getId(), true, fieldList);

            /*添加标签打印日志记录*/
            addLogRecordMseeage(formDataMasterBean);
        } catch (Exception e) {
            log.error("更新入库标签打印数据打印状态报错信息:", e);
        }

    }

    /**
     * 根据数据ID，查询FormDataMasterBean对象
     *
     * @param formDataId
     * @return
     */
    private static FormDataMasterBean getDataMasterBeanById(Long formDataId) {
        log.info("入库标签打印数据ID:" + formDataId);
        FormDataMasterBean formDataMasterBean = null;
        try {
            FormBean formBean = cap4FormManager.getFormByFormCode(unFlowformCode);
            formDataMasterBean = cap4FormManager.getDataMasterBeanById(formDataId, formBean, null);
        } catch (Exception e) {
            log.error("根据数据ID查询入库标签打印数据信息失败:", e);
        }
        return formDataMasterBean;
    }

    /**
     * 添加标签打印日志记录信息
     *
     * @param formDataMasterBean
     * @return
     */
    private static void addLogRecordMseeage(FormDataMasterBean formDataMasterBean) {
        try {

            FormBean rzjl_formBean = cap4FormManager.getFormByFormCode(rzjltaCode);
            FormDataMasterBean dataMasterBean = FormDataMasterBean.newInstance(rzjl_formBean);

            String gysVlaue = StrKit.str(formDataMasterBean.getFieldValue(formDataMasterBean.getFormTable().getFieldBeanByDisplay("供应商").getName()));
            String rkphVlaue = StrKit.str(formDataMasterBean.getFieldValue(formDataMasterBean.getFormTable().getFieldBeanByDisplay("入库批号").getName()));
            String wlmcVlaue = StrKit.str(formDataMasterBean.getFieldValue(formDataMasterBean.getFormTable().getFieldBeanByDisplay("物料名称").getName()));
            String wlbmVlaue = StrKit.str(formDataMasterBean.getFieldValue(formDataMasterBean.getFormTable().getFieldBeanByDisplay("物料编码").getName()));
            String xmbhVlaue = StrKit.str(formDataMasterBean.getFieldValue(formDataMasterBean.getFormTable().getFieldBeanByDisplay("项目编号").getName()));

            dataMasterBean.addFieldValue(dataMasterBean.getFormTable().getFieldBeanByDisplay("供应商").getName(), gysVlaue);
            dataMasterBean.addFieldValue(dataMasterBean.getFormTable().getFieldBeanByDisplay("入库批号").getName(), rkphVlaue);
            dataMasterBean.addFieldValue(dataMasterBean.getFormTable().getFieldBeanByDisplay("物料名称").getName(), wlmcVlaue);
            dataMasterBean.addFieldValue(dataMasterBean.getFormTable().getFieldBeanByDisplay("物料编码").getName(), wlbmVlaue);
            dataMasterBean.addFieldValue(dataMasterBean.getFormTable().getFieldBeanByDisplay("项目编号").getName(), xmbhVlaue);
            String ip = StrKit.str(IpKit.getLocalIp4Address().get().getHostAddress());
            dataMasterBean.addFieldValue(dataMasterBean.getFormTable().getFieldBeanByDisplay("打印设备地址").getName(), ip);
            dataMasterBean.addFieldValue(dataMasterBean.getFormTable().getFieldBeanByDisplay("打印日期").getName(), new Date());
            dataMasterBean.addFieldValue(dataMasterBean.getFormTable().getFieldBeanByDisplay("打印人").getName(), AppContext.getCurrentUser().getId());
            addUnFlowFormDataCap4(dataMasterBean, rzjl_formBean);
        } catch (Exception e) {
            log.error("标签打印日志记录报错信息:", e);
        }
    }

    /**
     * 新增无流程表单主表数据
     *
     * @param formDataMasterBean
     * @param formBean
     */
    private static void addUnFlowFormDataCap4(FormDataMasterBean formDataMasterBean, FormBean formBean) {
        try {
            Long userId = AppContext.getCurrentUser().getId();
            FormAuthViewBean formAuthViewBean = formBean.getNewFormAuthViewBeans().get(0);
            String rightid = String.valueOf(formAuthViewBean.getId());
            cap4FormDataManager.insertOrUpdateMasterData(formDataMasterBean);
            Long masterId = formDataMasterBean.getId();
            //正文内容保存
            int moduleType = getModuleTypeCap4(formBean);
            MainbodyService mainBodyService = MainbodyService.getInstance();
            CtpContentAll ctpContentAll = mainBodyService.getContent(moduleType, masterId);
            ctpContentAll = saveContentAllForFormCap4(ctpContentAll, masterId, userId, formBean, rightid);
            mainBodyService.saveOrUpdateContentAll(ctpContentAll);
        } catch (Exception e) {
            log.error("新增无流程表单数据报错信息:", e);
        }
    }


    private static CtpContentAll saveContentAllForFormCap4(CtpContentAll ctpContentAll, long masterId, long userid, FormBean formBean, String rightId) throws BusinessException {
        Timestamp timestamp = DateUtil.currentTimestamp();
        if (ctpContentAll != null) {    //存在就不新增了，否则导致同步后的无流程表单修改的时候会多出视图（ctp_content_all会多数据）
            ctpContentAll.setModifyId(userid);
            ctpContentAll.setModifyDate(timestamp);
            return ctpContentAll;
        }
        CtpContentAllBean content = new CtpContentAllBean();
        FormBindBean bindBean = formBean.getBind();
        if (bindBean != null) {
            content.setModuleTemplateId(bindBean.getId());
            Map<String, FormBindAuthBean> bindAuth = bindBean.getUnFlowTemplateMap();
            if (CollectionUtils.isEmpty(bindAuth.values())) {
                throw new BusinessException("无应用绑定");
            }
            for (FormBindAuthBean authBean : bindAuth.values()) {
                content.setTitle(authBean.getName());
            }
        }
        content.setModuleType(getModuleTypeCap4(formBean));
        content.setCreateId(userid);
        content.setCreateDate(timestamp);
        content.setSort(0);
        content.setId(UUIDLong.longUUID());
        content.setStatus(MainbodyStatus.STATUS_POST_SAVE);
        content.setContentType(Integer.valueOf(MainbodyType.FORM.getKey()));
        content.setContentTemplateId(formBean.getId());
        content.setContentDataId(masterId);
        content.setModuleId(masterId);
        content.setModifyDate(timestamp);
        content.setModifyId(userid);
        content.setRightId(rightId);

        return content.toContentAll();
    }

    /**
     * 获取cap4表单类型
     *
     * @param formBean
     * @return
     * @throws BusinessException
     */
    private static int getModuleTypeCap4(FormBean formBean) throws BusinessException {
        int moduleType = 0;
        if (formBean.getFormType() == 6) {
            moduleType = ModuleType.cap4UnflowForm.getKey();
        }
        if (moduleType == 0) {
            log.warn("无效表类型");
            throw new BusinessException("内容保存失败");
        }
        return moduleType;
    }

}
